package com.utils.basejava.concurrent.map;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.ForkJoinTask;
import java.util.concurrent.Future;
import java.util.concurrent.RecursiveTask;

public class ForkJoinTest extends RecursiveTask<Integer>{
	private static final int THRESHOLD = 2;//阈值

	private int start;
	private int end;
	
	public ForkJoinTest(int start, int end) {
		this.start = start;
		this.end = end;
	}
	
	@Override
	protected Integer compute() {
		System.out.println(start+","+end);
		int sum = 0;
		if(end-start>THRESHOLD) {
			int middle = (start+end)/2;
			ForkJoinTest s = new ForkJoinTest(start, middle);
			ForkJoinTest e = new ForkJoinTest(middle+1, end);
			s.fork();
			e.fork();
			sum = s.join()+e.join();
		}else {
			for (int i = start; i <= end; i++) {
				sum = sum+i;
			}
		}
		
		return sum;
	}
	
	public static void main(String[] args) {
		ForkJoinPool fjp = new ForkJoinPool();
		ForkJoinTest s = new ForkJoinTest(1, 100);
		
//		ForkJoinTask<Integer> result = fjp.submit(s);
		Future<Integer> result = fjp.submit(s);
		
		try {
			System.out.println(result.get());
		} catch (InterruptedException e) {
			e.printStackTrace();
		} catch(ExecutionException e1) {
			e1.printStackTrace();
		}

	}

}
